<p>
    {#if numUsers === 1} { __('teams / total / 1') } {:elseif numUsers > 1}
    <!-- prettier-ignroe -->
    { __('teams / total').replace('%i%', numUsers) } {/if} { @html numChartsCaption }
</p>

{#if sortedUsers.length}
<TableDisplay columnHeaders="{userHeaders}">
    {#each sortedUsers as user, i}
    <tr>
        <td>{ user.email }</td>
        {#if isAdmin}
        <td>
            <a href="/admin/users/{user.id}">{ user.id }</a>
        </td>
        {/if}
        <td>{ user.charts }</td>
        <td>
            {#if editId === user.id }
            <SelectInput bind:value="user.role" width="200px" options="{roles}" />
            <p class="mini-help">{ __('teams / role / p' ) }</p>
            {:else} {@html role(user.role) } {#if user.token}
            <i>{ __('teams / invite-pending' ) } </i>
            {/if} {/if}
        </td>
        <td>
            {#if (isAdmin && !isTeamOwner) || (isTeamOwner && user.id !== userId) || (isTeamAdmin &&
            user.role !== 'owner') } {#if editId === user.id }
            <button on:click="toggleEdit(user.id)" class="btn btn-primary">
                <i class="fa fa-check"></i>&nbsp; { __('teams / save' ) }
            </button>
            {:elseif updating[user.id]}
            <button disabled class="btn btn-primary">
                <i class="fa fa-spin fa-circle-o-notch"></i>&nbsp; { __('teams / save' ) }
            </button>
            {:else}
            <button on:click="toggleEdit(user.id)" class="btn">
                <i class="fa fa-edit"></i>&nbsp; { __('teams / edit' ) }
            </button>

            <button on:click="removeUser(user)" class="btn">
                <i class="fa fa-times"></i>&nbsp; { __('teams / remove' ) }
            </button>
            {/if} {:elseif isTeamOwner && (user.role === 'owner')}
            <p class="mini-help">{ __('teams / edit-role / owner / info') }</p>
            {/if}
        </td>
    </tr>
    {/each}
</TableDisplay>

{/if}

<ConfirmationModal
    ref:confirmationModal
    confirmButtonText="{__('teams / change-owner-confirmation / confirm')}"
    backButtonText="{__('teams / change-owner-confirmation / back')}"
    id="modalConfirmation"
    title="{ownerChangeTitle}"
    on:confirm="updateRole(editId)"
>
    <p>{@html ownerChangeMessage}</p>
    {#if products.length}
    <AlertDisplay type="'warning'" closeable="{false}" visible="{true}" class="spacing-helper">
        <div class="confirmation-warning">
            {@html __('teams / change-owner-confirmation / warning')}
        </div>
    </AlertDisplay>
    {/if}
</ConfirmationModal>

<script>
    import TableDisplay from '@datawrapper/controls/TableDisplay.html';
    import SelectInput from '@datawrapper/controls/SelectInput.html';
    import ConfirmationModal from '@datawrapper/controls/ConfirmationModal.html';
    import AlertDisplay from '@datawrapper/controls/AlertDisplay.html';
    import { __ } from '@datawrapper/shared/l10n';
    import httpReq from '@datawrapper/shared/httpReq';

    const teamRoleOptions = [
        { value: 'owner', label: __('teams / role / owner').replace('&shy;', '') },
        { value: 'admin', label: __('teams / role / admin').replace('&shy;', '') },
        { value: 'member', label: __('teams / role / member').replace('&shy;', '') }
    ];

    export default {
        components: { TableDisplay, SelectInput, ConfirmationModal, AlertDisplay },
        data() {
            return {
                editId: false,
                updating: {},
                users: [],
                products: []
            };
        },
        computed: {
            roles({ isAdmin, isTeamOwner }) {
                return isAdmin || isTeamOwner ? teamRoleOptions : teamRoleOptions.slice(1);
            },
            sortedUsers({ users, isAdmin }) {
                return users
                    .sort((a, b) => {
                        const roles = ['owner', 'admin', 'member'];

                        if (roles.indexOf(a.role) > roles.indexOf(b.role)) {
                            return 1;
                        } else if (roles.indexOf(a.role) < roles.indexOf(b.role)) {
                            return -1;
                        } else {
                            return a.email > b.email ? 1 : a.email < b.email ? -1 : 0;
                        }
                    })
                    .filter(user => isAdmin || !user.isAdmin);
            },
            userHeaders({ isAdmin }) {
                const userHeaders = [
                    { title: __('teams / user'), width: '25%' },
                    { title: 'ID', width: '10%' },
                    { title: 'Charts', width: '15%' },
                    { title: __('teams / status'), width: '15%' },
                    { title: __('teams / actions'), width: '30%' }
                ];

                if (!isAdmin) userHeaders.splice(1, 1);

                return userHeaders;
            },
            numUsers({ sortedUsers }) {
                return sortedUsers.length;
            },
            numCharts({ users }) {
                let total = 0;
                users.forEach(user => {
                    total += user.charts;
                });
                return total;
            },
            numChartsCaption({ numCharts, isAdmin, team }) {
                if (numCharts === 1) {
                    return __('teams / charts-total / 1');
                } else if (numCharts > 1) {
                    if (isAdmin) {
                        return __('teams / charts-total-admin')
                            .replace('%i%', numCharts)
                            .replace('%link%', `/admin/chart/by/${team.id}`);
                    } else {
                        return __('teams / charts-total').replace('%i%', numCharts);
                    }
                } else {
                    return '';
                }
            },
            ownerChangeMessage({ users, editId, team, isTeamOwner }) {
                const user = users.find(u => u.id === editId);
                const owner = users.find(u => u.id !== editId && u.role === 'owner');
                const userEmail = user ? user.name || user.email || user.id : 'non-existent';
                const ownerEmail = owner ? owner.name || owner.email || owner.id : 'non-existent';
                return __('teams / change-owner-confirmation / message')
                    .replace('%member%', `<b>${userEmail}</b>`)
                    .replace(
                        '%message%',
                        isTeamOwner
                            ? __('teams / change-owner-confirmation / owner-message')
                            : __('teams / change-owner-confirmation / non-owner-message').replace(
                                  '%member%',
                                  `<b>${ownerEmail}</b>`
                              )
                    )
                    .replace('%team%', `<b>${team.name}</b>`);
            },
            ownerChangeTitle({ users, editId }) {
                const user = users.find(u => u.id === editId);
                const userEmail = user ? user.name || user.email || user.id : 'non-existent';
                return __('teams / change-owner-confirmation / title').replace(
                    '%member%',
                    userEmail
                );
            }
        },
        helpers: {
            role(role) {
                return {
                    member: __('teams / role / member'),
                    admin: __('teams / role / admin'),
                    owner: __('teams / role / owner')
                }[role];
            },
            __
        },
        methods: {
            toggleEdit(userId) {
                if (this.get().editId === userId) {
                    this.requestUpdateRole(userId);
                } else {
                    this.set({
                        editId: userId
                    });
                }
            },
            async removeUser(user) {
                if (!window.confirm(__('teams / remove / alert'))) return;

                await httpReq.delete(`/v3/teams/${this.get().team.id}/members/${user.id}`);

                var { users } = this.get();
                users = users.filter(el => el.id !== user.id);
                this.set({ users });
            },
            async requestUpdateRole(userId) {
                var { users } = this.get();
                const user = users.filter(u => u.id === userId)[0];

                if (user.role === 'owner') {
                    // ownership transfer --> ask for confirmation first
                    this.refs.confirmationModal.open();
                    return;
                }
                await this.updateRole(userId);
            },
            async updateRole(userId) {
                var { updating, users } = this.get();
                const user = users.filter(u => u.id === userId)[0];
                updating[user.id] = true;
                this.set({ updating });

                await httpReq.put(`/v3/teams/${this.get().team.id}/members/${user.id}/status`, {
                    payload: {
                        status: user.role
                    }
                });

                updating = this.get().updating;
                updating[user.id] = false;
                this.set({ updating, editId: false });
                this.fire('updateUsers');
            }
        }
    };
</script>
<style>
    .confirmation-warning {
        white-space: pre-line;
    }
</style>
